package com.endurance.compoent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class ConnectionFactory {

    @Autowired
    ThreadLocal<Connection> threadLocal;

    @Autowired
    DataSource dataSource;

    public Connection currentThreadConn() {
        // 1. 先尝试 ThreadLocal 中获取当前线程连接
        Connection connection = threadLocal.get();
        // 2. 判断当前线程是否有连接
        if (connection == null) {
            try {
                // 3. 从连接池中获取一个连接
                connection = dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException();
            }
            // 4. 将连接与当前线程绑定
            threadLocal.set(connection);
        }
        // 5. 返回连接
        return connection;
    }


}
